package com.demo.reservation.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.reservation.domain.PetInfo;
import com.demo.reservation.domain.Reservation;
import com.demo.reservation.domain.Userinfo;
import com.demo.reservation.dto.CreateReservation;
import com.demo.reservation.dto.ReservationQueryParam;
import com.demo.reservation.mapper.ReservationMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
@Slf4j
public class ReservationService extends ServiceImpl<ReservationMapper, Reservation> {
    @Resource
    private ReservationMapper reservationMapper;
    @Resource
    private PetInfoService petInfoService;
    @Resource
    private UseinfoService useinfoService;

    public IPage<Reservation> search(ReservationQueryParam param) {
        return reservationMapper.searchByParam(param.getPageParam(),
                param.getUserName(), param.getUserPhone());
    }

    @Transactional
    public Reservation create(CreateReservation data) {
        Reservation reservation = new Reservation();
        reservation.setReserveTime(data.getReserveTime());
        reservation.setReason(data.getReason());
        // 保存用户信息
        Userinfo u = new Userinfo();
        u.setName(data.getUsername());
        u.setPhone(data.getPhone());
        u = useinfoService.create(u);
        reservation.setUserinfo(u);
        log.debug("创建用户信息成功:{}", u.getId());
        // 保存宠物信息
        PetInfo pet = new PetInfo();
        pet.setName(data.getPetName());
        pet.setCategory(data.getPetCategory());
        pet.setUid(u.getId());
        pet = petInfoService.create(pet);
        reservation.setPetInfo(pet);
        log.debug("创建宠物信息成功:{}", pet.getId());
        reservation.setUid(u.getId());
        reservation.setPetId(pet.getId());
        reservationMapper.insert(reservation);
        return reservation;
    }
}
